package io.wdb.wxapp.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wdb.exchange.constant.EventEnum;
import com.wdb.exchange.constant.SourceEnum;
import com.wdb.exchange.model.Event;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.wdb.common.exception.RspCodeEnum;
import io.wdb.common.utils.ConstantConfig;
import io.wdb.common.utils.R;
import io.wdb.config.AmqpConfig;
import io.wdb.handler.AmqpSendHandler;
import io.wdb.handler.ApiServiceHandler;
import io.wdb.modules.activity.wxapp.entity.HdActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdLotteryActivityConvertInfoEntity;
import io.wdb.modules.activity.wxapp.entity.HdLotteryActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdLotteryUserInfoEntity;
import io.wdb.modules.activity.wxapp.entity.HdUserEntity;
import io.wdb.modules.activity.wxapp.entity.LocationCountEntity;
import io.wdb.modules.activity.wxapp.service.HdActivityService;
import io.wdb.modules.activity.wxapp.service.HdLotteryActivityService;
import io.wdb.modules.activity.wxapp.service.HdLotteryUserInfoService;
import io.wdb.modules.activity.wxapp.service.HdUserService;
import io.wdb.wxapp.model.HdLotteryActivityModel;
import io.wdb.wxapp.model.HdLotteryUserInfoModel;

@Controller
@RequestMapping("lottery")
@Api(tags="E.lotteryActivity api" ) 
public class HdLotteryController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(HdLotteryController.class);
	
	@Autowired
	HdLotteryActivityService hdLotteryActivityService;
	@Autowired
	private ApiServiceHandler apiServiceHandler ;
	@Autowired
	HdActivityService hdActivityService;
	@Autowired
	HdUserService hdUserService;
	@Autowired
	AmqpSendHandler amqpSendHandler;
	
	@Autowired
	HdLotteryUserInfoService hdLotteryUserInfoService;
	
	@RequestMapping(value = "getLotteryInfo", method = RequestMethod.POST)
	@ApiOperation(value = "获取抽奖数据", notes = "前置请求getOpenid接口活动usertoken，再请求获取抽奖信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userid", value = "userid", dataType = "Long", paramType = "query", required = false),
			@ApiImplicitParam(name = "parentHdUid", value = "分享者hduserid", dataType = "Long", paramType = "query", required = false),
			@ApiImplicitParam(name = "usertoken", value = "测试用，实际header中已有", dataType = "Long", paramType = "query", required = false),
			@ApiImplicitParam(name = "activityId", value = "活动Id，定值:lotteryInfo001", dataType = "String", paramType = "query", required = true)})
	@ResponseBody
	public R getLotteryInfo(HttpServletRequest request) {
		// 奖券信息
		logger.info("getLotteryInfo request param:{}",getParams(request));
		String usertoken =request.getParameter("usertoken");
		if(isEmpty(usertoken)) {
			usertoken = request.getHeader("token");
		}
		String activityId = request.getParameter("activityId");
		String userid = request.getParameter("userid");
		String mobile = request.getParameter("mobile");
		String parentUserid = request.getParameter("parentHdUid");

		checkIsNull(usertoken, "usertoken");
		checkIsNull(activityId, "activityId");
		
		HdUserEntity userinfo = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);
		if(isEmpty(userinfo)) {
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		
		if(isEmpty(userid) && !isEmpty(userinfo.getApiUserId())) {
			userid = userinfo.getApiUserId().toString();
		}
		
		Event event = new Event();
		event.userId = userinfo.getApiUserId();
		event.source = SourceEnum.ACTIVITY;
		event.event = EventEnum.AWARD_VIEW;
		event.openId = userinfo.getWxOpenid();
		event.appId = userinfo.getWxAppid();
		event.mobile = userinfo.getMobile();
		event.eventTime = new Date().getTime();
		//数据统计
		amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
		
		String hdUserid= userinfo.getId();
		int lotteryCount = lotteryCount(hdUserid, userid);//初始抽奖次数
		
		//根据activityId查询活动是否开启
		HdActivityEntity activityInfo = hdActivityService.queryObject(activityId);
		if(isEmpty(activityInfo) || (activityInfo.getAvailable() == 0)) {
			logger.info("activity is end :{}:{}",RspCodeEnum.LOTTERY_ACTIVITY_END.getRspCode(), RspCodeEnum.LOTTERY_ACTIVITY_END.getRspMsg());
			return R.error(RspCodeEnum.LOTTERY_ACTIVITY_END.getRspCode(), RspCodeEnum.LOTTERY_ACTIVITY_END.getRspMsg());
		}
		
		Map<String, Object> sql = new HashMap<String, Object>();
		//根据activityId查询奖品
		sql.put("filterSql", " activity_id = '" + activityId.replace("'", "") + "' and status = 0");
		List<HdLotteryActivityEntity> lotteryActivityEntities = hdLotteryActivityService.queryList(sql);
		
		if(isEmpty(lotteryActivityEntities)) {
			return R.error(RspCodeEnum.LOTTERY_ACTIVITY_END.getRspCode(), RspCodeEnum.LOTTERY_ACTIVITY_END.getRspMsg());
		}
		
		Map<String, Object> userResult = new HashMap<>();
		userResult.put("lotteryCount", lotteryCount);
		userResult.put("hdUserid", hdUserid);//分享时需要
		//TODO detail返回个人信息如：抽奖次数；items放置奖品信息
		if(lotteryCount > 0) {
			//返回中奖数据
			userResult.putAll(getPersonalLottery(userid, lotteryCount, activityId, hdUserid, parentUserid, userinfo.getNewUser(), lotteryActivityEntities));
		}//次数不足直接不返回
		logger.info(" getLotteryInfo userResult end :{}", userResult);
		return R.ok().put("detail", userResult).put("items", HdLotteryActivityModel.convert(lotteryActivityEntities));
	}

	@RequestMapping(value = "receivePersonalLottery", method = RequestMethod.POST)
	@ApiOperation(value = "抽奖", notes = "返回loterryAwardId后，才能点击抽奖")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "loterryAwardId", value = "loterryAwardId", dataType = "String", paramType = "query", required = false)
			})
	@ResponseBody
	public R receivePersonalLottery(HttpServletRequest request) {
		logger.info("receivePersonalLottery request param:{}",getParams(request));
		String loterryAwardId = request.getParameter("loterryAwardId");
		HdLotteryUserInfoEntity lotteryUserinfo = hdLotteryUserInfoService.queryObject(loterryAwardId);
		if(isEmpty(lotteryUserinfo)) {
			return R.error(RspCodeEnum.LOTTERY_ACTIVITY_ERROR.getRspCode(), RspCodeEnum.LOTTERY_ACTIVITY_ERROR.getRspMsg());
		}
		
		//TODO 返回界面的抽奖信息
		Map<String, Object> lotteryInfo = new HashMap<>();
		String couponCode = lotteryUserinfo.getHdLotteryActivityId();
		HdLotteryActivityEntity hdLotteryActivityEntity = hdLotteryActivityService.queryObject(couponCode);
		String[] contentString = hdLotteryActivityEntity.getLotteryRule().split(";");
		lotteryInfo.put("lotteryName", contentString[0]);//中奖名称
		lotteryInfo.put("lotteryContent", contentString[1]);//中奖券使用详情
		if(contentString.length > 2 && !isEmpty(contentString[2])) {
			lotteryInfo.put("lotterySuccessContent", contentString[2]);//中奖券使用详情
		}else {
			lotteryInfo.put("lotterySuccessContent", contentString[1]);//中奖券使用详情
		}
		lotteryInfo.put("lotteryType",hdLotteryActivityEntity.getType());
		if(!isEmpty(hdLotteryActivityEntity.getLotteryCode())) {
			lotteryInfo.putAll(apiServiceHandler.couponBookShelfInfo(hdLotteryActivityEntity.getLotteryCode()));
		}

		//点击抽奖，更新status为
		if(ConstantConfig.LOTTERY_STATUS_INIT.equals(lotteryUserinfo.getLotteryStatus())) {
			//更新奖品状态
			HdLotteryUserInfoEntity updateLotteryUserinfo = new HdLotteryUserInfoEntity();
			updateLotteryUserinfo.setId(lotteryUserinfo.getId());
			//判断是否存在api的userid，对应的借阅记录是否>0
			if(!isEmpty(lotteryUserinfo.getApiUserId())  && apiServiceHandler.returnBookCount(lotteryUserinfo.getApiUserId().toString()) > 0) {
				int currentBorrowChanceCount = hdLotteryUserInfoService.currentBorrowChanceCount(lotteryUserinfo.getHdUserId(), lotteryUserinfo.getApiUserId());
				if(currentBorrowChanceCount < 1) {
					updateLotteryUserinfo.setBorrowChance(ConstantConfig.BORROW_CHANCE_YES);
					lotteryUserinfo.setBorrowChance(ConstantConfig.BORROW_CHANCE_YES);
					logger.info("no used borrowChance and lottery chance plus 1");
				}
			}
			
			if(isEmpty(lotteryUserinfo.getApiUserId())) {
				updateLotteryUserinfo.setUserStatus(ConstantConfig.LOTTERY_USER_STATUS_UNLOGIN);//未登录
				updateLotteryUserinfo.setLotteryStatus(ConstantConfig.LOTTERY_STATUS_UNSEND);//默认是不发放
				hdLotteryUserInfoService.update(updateLotteryUserinfo);
				
				lotteryInfo.put("loginStatus", ConstantConfig.LOTTERY_USER_STATUS_UNLOGIN);
				logger.info("receivePersonalLottery lotteryInfo LOTTERY_USER_STATUS_UNLOGIN end:{}", lotteryInfo);

				//返回前端，需要登录
				return R.error(RspCodeEnum.LOTTERY_ACTIVITY_UNLOGIN.getRspCode(), RspCodeEnum.LOTTERY_ACTIVITY_UNLOGIN.getRspMsg()).put("detail", lotteryInfo);
			}else {
				//已登录，异步发券，更新状态
				lotteryInfo.put("loginStatus", ConstantConfig.LOTTERY_USER_STATUS_LOGINED);
				hdLotteryUserInfoService.sendLotteryAward(lotteryUserinfo, hdLotteryActivityEntity);
			}
			
		}else {
			//接口重复调用
			return R.error(RspCodeEnum.LOTTERY_ACTIVITY_REPEAT.getRspCode(), RspCodeEnum.LOTTERY_ACTIVITY_REPEAT.getRspMsg());
		}
		
		logger.info("receivePersonalLottery lotteryInfo LOTTERY_USER_STATUS_LOGINED end:{}", lotteryInfo);
		
		return R.ok(lotteryInfo);
	}
	
	@RequestMapping(value = "listFriendsLottery", method = RequestMethod.POST)
	@ApiOperation(value = "好友抽奖信息", notes = "listFriendsLottery")
	@ApiImplicitParams({
	@ApiImplicitParam(name = "userid", value = "userid", dataType = "Long", paramType = "query", required = false),
	@ApiImplicitParam(name = "usertoken", value = "测试用，实际header中已有", dataType = "Long", paramType = "query", required = false),
	@ApiImplicitParam(name = "pagesize", value = "分页参数", dataType = "Integer", paramType = "query", required = false),
	@ApiImplicitParam(name = "pageno", value = "分页参数", dataType = "Integer", paramType = "query", required = false),
	@ApiImplicitParam(name = "activityId", value = "活动Id，定值:lotteryInfo001", dataType = "String", paramType = "query", required = true)
	})
	@ResponseBody
	public R listFriendsLottery(HttpServletRequest request) {
		logger.info("listFriendsLottery request param:{}",getParams(request));
		String userid = request.getParameter("userid");
		String usertoken = request.getParameter("usertoken");
		if(isEmpty(usertoken)){
			usertoken = request.getHeader("usertoken");
		}
		HdUserEntity userinfo = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, null);
		if(isEmpty(userinfo)) {
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		//根据hdUserId查询
		String hdUserid = userinfo.getId();
		
		String pagesize = request.getParameter("pagesize");
		String pagno = request.getParameter("pageno");
		Map<String, Object> sql = new HashMap<>();
		if(!isEmpty(pagesize) && !isEmpty(pagno)) {
			sql.put("offset", (Integer.valueOf(pagno)-1) * Integer.valueOf(pagesize));
			sql.put("limit", Integer.valueOf(pagesize));
		}
		sql.put("hdUserId", hdUserid);
		List<HdLotteryActivityConvertInfoEntity> entities = hdLotteryUserInfoService.listFriendsLottery(sql);
		List<HdLotteryUserInfoModel> models = HdLotteryUserInfoModel.convert(entities);
		logger.info("listFriendsLottery request end:{}",models);
		return R.ok().put("items", models);
	}
	
	/**
	 * 剩余抽奖次数
	 * @param hdUserid
	 * @param userid
	 * @return
	 */
	private int lotteryCount(String hdUserid, String userid) {
		int lotteryCount = Integer.valueOf(getConfig("initLotteryCount"));// 初始抽奖次数
		int parentShareCount = hdLotteryUserInfoService.parentShareLotteryCount(hdUserid);// 邀请好友获得抽奖次数
		int returnBookeCount = 0;
		if(!isEmpty(userid)) {
			if(apiServiceHandler.returnBookCount(userid) > 0) {
				returnBookeCount = 1;
			}
		}

		int userCount = hdLotteryUserInfoService.usedLotteryCount(hdUserid, userid);// 用户使用次数
		int usedBorrowChance = hdLotteryUserInfoService.usedBorrowChance(hdUserid);//借阅产生的抽奖次数
		int count = lotteryCount + parentShareCount + returnBookeCount - userCount + usedBorrowChance;
		if (count < 0) {
			count = 0;
		}
		return count;
	}
	
	/**
	 * 抽奖结果数据
	 * @param userid 当前api用户id
	 * @param lotteryCount 抽奖次数
	 * @param activityId 活动id
	 * @param hdUserid 活动用户id
	 * @param parentUserid 分享者id
	 * @return
	 */
	private Map<String, Object> getPersonalLottery(String useridStr,
			int lotteryCount, String activityId, String hdUserid, 
			String parentUserid, int newUser,List<HdLotteryActivityEntity> allLotteryActivities) {
		//TODO 查询当前用户当天抽奖次数
		Map<String, Object> result = new HashMap<>();
		if(lotteryCount > 0) {
			int location = randomLottery(activityId, hdUserid, useridStr, allLotteryActivities, newUser);
			Map<String, Object> sql = new HashMap<String, Object>();
			//根据activityId查询奖品
			sql.put("filterSql", " activity_id = '"+ activityId +"' and status = 0 and location = "+ location);
			/*此处只能返回一个奖品*/
			List<HdLotteryActivityEntity> lotteryActivityEntities = hdLotteryActivityService.queryList(sql);
			
			HdLotteryActivityEntity lotteryInfo = null;
			//获取当前抽奖的数据，返回前端
			for(HdLotteryActivityEntity info:allLotteryActivities) {
				if(info.getLocation().equals(location)) {
					lotteryInfo = info;
					logger.info("lottery info id{}", info.getId());
				}
			}
			//未查询到奖品，提示活动结束
			lotteryInfo = lotteryActivityEntities.get(0);
			if(isEmpty(lotteryInfo)) {
				logger.info("抽奖异常:activityId:{},hdUserid:{}", activityId , hdUserid);
				
			}else {
				//返回前端中奖活动信息
				Map<String, Object> detail = new HashMap<>();
				detail.put("location", location);//抽奖后指针停留位置
				detail.put("lotteryName", lotteryInfo.getLotteryName());//中奖名称
//				detail.put("lotteryContent", lotteryInfo.getLotteryRule());//中奖券使用详情
				
				//TODO 抽中奖品存储
				HdLotteryUserInfoEntity hdLotteryUserInfo = new HdLotteryUserInfoEntity();
				hdLotteryUserInfo.setCreateTime(new Date());
				hdLotteryUserInfo.setHdLotteryActivityId(lotteryInfo.getId());
				hdLotteryUserInfo.setLotteryStatus(ConstantConfig.LOTTERY_STATUS_INIT);//初始进入抽奖界面返回的结果
				hdLotteryUserInfo.setHdUserId(hdUserid);
				//parentUserid存储
				if(!isEmpty(parentUserid)) {
					hdLotteryUserInfo.setParentUserId(parentUserid);
				}
				hdLotteryUserInfo.setNewUser(newUser);
				//用户信息存储
				if(isEmpty(useridStr)) {
					hdLotteryUserInfo.setUserStatus(ConstantConfig.LOTTERY_USER_STATUS_UNLOGIN);
				}else {
					hdLotteryUserInfo.setUserStatus(ConstantConfig.LOTTERY_USER_STATUS_LOGINED);
					hdLotteryUserInfo.setApiUserId(Long.valueOf(useridStr));
				}
				//奖品id
				String loterryAwardId = hdLotteryUserInfoService.save(hdLotteryUserInfo);
				detail.put("loterryAwardId", loterryAwardId);//获得奖品id
				result.put("lotteryInfo", detail);
			}
		}
		return result;
	}

	/**
	 * 抽中奖品设置
	 * @param activityId
	 * @param hdUserid
	 * @param userid
	 * @param lotteryActivities
	 * @param newUser
	 * @return
	 */
	private int randomLottery(String activityId, String hdUserid, String userid, List<HdLotteryActivityEntity> lotteryActivities, int newUser) {
		//查询是否第一次
		int firstCount = hdLotteryUserInfoService.usedLotteryCount(hdUserid, userid);
		//2，4，6
		String[] defaultLocations = getConfig("defaultLocations").split(",");
		int defaultIndex = new Random().nextInt(defaultLocations.length);
		int defaultLocation = Integer.valueOf(defaultLocations[defaultIndex]);
		
		int selectedIndex = defaultLocation;
		if(firstCount > 0) {//不是第一次抽奖
			selectedIndex = otherPrize(lotteryActivities);
		}else {//第一次抽奖
			String lotteryRate;
			if(ConstantConfig.NEW_USER_YES.equals(newUser)) {
				lotteryRate = getConfig("firstLotteryRateNewUser");//新用户第一次抽奖概率
			}else {
				lotteryRate = getConfig("firstLotteryRateOldUser");//老用户第一次抽奖概率
			}
			selectedIndex = firstPrizeIndex(lotteryActivities, lotteryRate);
		}

		//==============整个活动奖品数限制 START================//
		//查询出所有中奖分布
		List<LocationCountEntity> allLotteryCount = hdLotteryUserInfoService.locationCountAll(activityId);
		String lotteryLocationAll = getConfig("lotteryLocationAll");
		if(limitLottery(lotteryLocationAll,allLotteryCount,selectedIndex) < 0) {
			logger.info("lottery lotteryLocationAll changes {} : {} : {}", hdUserid,selectedIndex, defaultLocation);
			selectedIndex = defaultLocation;
		}
		//==============整个活动奖品数限制 END================//
		
		//==============每一位用户只能获得一本绘本或者一张年卡，后台可配 START==========//
		//每人限制
		List<LocationCountEntity> lotteryLocationPerManCount = hdLotteryUserInfoService.lotteryLocationPerMan(activityId,hdUserid);
		String lotteryLocationPerMan = getConfig("lotteryLocationPerMan");
		if(limitLottery(lotteryLocationPerMan, lotteryLocationPerManCount, selectedIndex) < 0) {
			logger.info("lottery lotteryLocationPerMan changes {} : {} : {}", hdUserid,selectedIndex, defaultLocation);
			selectedIndex = defaultLocation;
		}
		//==============每一位用户只能获得一本绘本或者一张年卡，后台可配 END==========//

		//===============每天限制 START==========//
		List<LocationCountEntity> lotteryLocationPerDayCount = hdLotteryUserInfoService.lotteryLocationPerDay(activityId);
		String lotteryLocationPerDay = getConfig("lotteryLocationPerDay");
		if(limitLottery(lotteryLocationPerDay, lotteryLocationPerDayCount, selectedIndex) < 0) {
			logger.info("lottery lotteryLocationPerDay changes {} : {} : {}", hdUserid,selectedIndex, defaultLocation);
			selectedIndex = defaultLocation;
		}
		//===============每天限制 END==========//
		
		//判断是否获得过绘本/年卡/
		if(!isEmpty(lotteryLocationPerManCount) && lotteryLocationPerManCount.size() > 0) {
			for(LocationCountEntity perMan:lotteryLocationPerManCount) {
				//3/7/8
				if(perMan.getLocation().equals(3) || perMan.getLocation().equals(7) || perMan.getLocation().equals(8)) {
					logger.info("判断是否获得过绘本-年卡,perMan.getLocation:{},getLocationCount:{},selectedIndex:{}",perMan.getLocation(), perMan.getLocationCount(), selectedIndex);
					if(perMan.getLocationCount() > 0 && (selectedIndex == 3 || selectedIndex == 7 || selectedIndex == 8)) {
						logger.info("lottery yearCard-bookCard changes {} : {} : {}", hdUserid,selectedIndex, defaultLocation);
						selectedIndex = defaultLocation;
					}
				}
			}
		}
		return selectedIndex;//中奖位置
	}
	/**
	 * 
	 * @param lotteryLocationLimit
	 * @param locationCountEntities
	 * @param defaultLocation
	 * @param selectedIndex
	 * @return
	 */
	private int limitLottery(String lotteryLocationLimit, List<LocationCountEntity> locationCountEntities, int selectedIndex) {
		String[] lotteryLocationAlls = lotteryLocationLimit.split(",");
		logger.info("{} data:[{}]", lotteryLocationLimit, lotteryLocationAlls);
		// 查询系统限制总数的标准，抽奖selectedIndex作为系统配置lotteryLocationAll的下标判断
		int limitLotteryCount = Integer.valueOf(lotteryLocationAlls[selectedIndex - 1]);
		logger.info("limitLottery selectedIndex {}, limitLotteryCount {}", selectedIndex, limitLotteryCount);
		if (limitLotteryCount > 0) {
			if (locationCountEntities != null && locationCountEntities.size() > 0) {
				for (LocationCountEntity perLotteryCount : locationCountEntities) {
					logger.info("perLotteryCount.getLocation():{},selectedIndex {}", perLotteryCount.getLocation(), selectedIndex);
					if (perLotteryCount.getLocation().equals(selectedIndex)) {
						logger.info("limitLottery selectedIndex {}, limitLotteryCount {},actualCount {}",selectedIndex,limitLotteryCount,(perLotteryCount.getLocationCount() + 1));
						if ((perLotteryCount.getLocationCount() + 1) > limitLotteryCount) {
							selectedIndex = -1;// TODO 当前中奖超过奖品限制，直接设置停留到继续努力
						}
					}
				}
			}
		}

		return selectedIndex;
	}
	
	protected int firstPrizeIndex(List<HdLotteryActivityEntity> prizes, String lotteryRate) {
		int random = -1;
		//重置抽奖概率
		String[] userFirstRate = lotteryRate.split(",");
		int userFirstRateLength = userFirstRate.length;
		for(int location=0;location < userFirstRateLength; location++) {
			prizes.get(location).setLotteryRate(Integer.valueOf(userFirstRate[location]));
		}
		
		try {
			// 计算总权重
			double sumWeight = 0;
			for (HdLotteryActivityEntity p : prizes) {
				sumWeight += p.getLotteryRate();
			}
			// 产生随机数
			double randomNumber = Math.random();
			// 根据随机数在所有奖品分布的区域并确定所抽奖品
			double d1 = 0;
			double d2 = 0;
			for (int i = 0; i < prizes.size(); i++) {
				d2 += Double.parseDouble(String.valueOf(prizes.get(i).getLotteryRate())) / sumWeight;
				if (i == 0) {
					d1 = 0;
				} else {
					d1 += Double.parseDouble(String.valueOf(prizes.get(i - 1).getLotteryRate())) / sumWeight;
				}
				if (randomNumber >= d1 && randomNumber <= d2) {
					random = i;
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("抽奖概率随机异常:{}",e.getMessage());
		}
		return random+1;
	}
	/**
	 * 奖励列表计算概率
	 * @param prizes
	 * @return
	 */
	protected int otherPrize(List<HdLotteryActivityEntity> prizes) {
		int random = -1;
		try {
			// 计算总权重
			double sumWeight = 0;
			for (HdLotteryActivityEntity p : prizes) {
				sumWeight += p.getLotteryRate();
			}
			// 产生随机数
			double randomNumber = Math.random();
			// 根据随机数在所有奖品分布的区域并确定所抽奖品
			double d1 = 0;
			double d2 = 0;
			for (int i = 0; i < prizes.size(); i++) {
				d2 += Double.parseDouble(String.valueOf(prizes.get(i).getLotteryRate())) / sumWeight;
				if (i == 0) {
					d1 = 0;
				} else {
					d1 += Double.parseDouble(String.valueOf(prizes.get(i - 1).getLotteryRate())) / sumWeight;
				}
				if (randomNumber >= d1 && randomNumber <= d2) {
					random = i;
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("抽奖概率随机异常:{}",e.getMessage());
		}
		return random+1;
	}
	
}
